<?php
/**
 * This file is part of the Yacms (http://www.yacms.org)
 * Copyright (c) 2019 gylr0505 (http://www.yacms.org)
 *
 * Author: 鬼一浪人 <gylr0505@163.com>
 *
 * DateTime: 19-10-27 下午5:43
 * Description:
 */
 
declare(strict_types = 1);

namespace App\Template\Queue;

class ConsumerIntervalControl
{
    const SEND_LIMIT_TOTAL_OF_ONE_MINUTE = 300;

    private static $_instance;

    /**
     * @var array
     * [
     *    'app_id' => '',
     *    'send_limit' => '300'
     * ]
     */
    private static $cache = [];

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public static function getInstance()
    {
        if (!self::$_instance){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * @param string $app_id
     * @param int $send_limit
     */
    public function load($app_id = '', $send_limit = self::SEND_LIMIT_TOTAL_OF_ONE_MINUTE)
    {
        if (!isset(self::$cache[$app_id])){
            self::$cache[$app_id] = [
                'send_limit' => $send_limit ?? self::SEND_LIMIT_TOTAL_OF_ONE_MINUTE,
                'counter' => 0,
                'is_fail' => false
            ];
        }
    }

    /**
     * @param string $app_id
     */
    public function notifyFail($app_id = '')
    {
        if (isset(self::$cache[$app_id])){
            self::$cache[$app_id]['is_fail'] = true;
        }
    }

    /**
     * @param string $app_id
     * @return bool
     */
    public function isFail($app_id = '')
    {
        if (!isset(self::$cache[$app_id])){
            return false;
        }
        return self::$cache[$app_id]['is_fail'];
    }

    /**
     * @param string $app_id
     * @return bool
     */
    public function isTop($app_id = '')
    {
        if (!isset(self::$cache[$app_id])){
            return true;
        }
        return self::$cache[$app_id]['counter'] >= self::$cache[$app_id]['send_limit'];
    }

    /**
     * @param string $app_id
     * @return bool
     */
    public function isNext($app_id = '')
    {
        if (!isset(self::$cache[$app_id])){
            return false;
        }
        if ($this->isFail($app_id)){
            return false;
        }
        if ($this->isTop($app_id)){
            return false;
        }

        return true;
    }

    /**
     * 发出模板消息请求时，总量增加1，无论成功与否
     * @param string $app_id
     */
    public function addCounterOnce($app_id = '')
    {
        if (isset(self::$cache[$app_id])){
            self::$cache[$app_id]['counter'] += 1;
        }
    }

    public function __destruct()
    {
        self::$cache = null;
    }
}